/**
 * 
 */
package util;

import org.hibernate.Criteria;
import org.hibernate.Session;
import org.hibernate.criterion.Order;
import org.hibernate.criterion.Restrictions;

import bean.NetResources;

import view.SearchResultsView;



/**
 * @author mareshkau
 *
 */
public class QueryBuilder {

	
	public static Criteria getListCriteria(Session session,SearchResultsView view,boolean order) {
		
		Criteria searchCriteria = session.createCriteria(NetResources.class);

		prepareSearchCriteria(searchCriteria, view,order);
		
		return searchCriteria;
	}
	
	private static void prepareSearchCriteria(Criteria  searchCriteria ,SearchResultsView view, boolean order){
		
//		if(view.getName()!=null&&view.getName().length()>0){
//			searchCriteria.add(Restrictions.like("name","%"+ view.getName()+"%"));
//		}
//		if(view.getServer()!=null&&view.getServer().length()>0) {
//			searchCriteria.add(Restrictions.like("server","%"+view.getServer()+"%"));
//		}
//		if(view.getExcludeServer()!=null && view.getServer().length()>0) {
//			searchCriteria.add(Restrictions.not(Restrictions.like("server","%"+view.getExcludeServer()+"%")));
//		}
//		
//		if(view.getPath()!=null&&view.getPath().length()>0) {
//			searchCriteria.add(Restrictions.like("path","%"+view.getPath()+"%"));
//		}
//		
//		if(view.getExcludePath()!=null&&view.getExcludePath().length()>0) {
//			searchCriteria.add(Restrictions.not(Restrictions.like("path","%"+view.getExcludePath()+"%")));
//		}
//		
//		if(view.getExcludeServer()!=null && view.getExcludeServer().length()>0) {
//			searchCriteria.add(Restrictions.not(Restrictions.like("server","%"+view.getExcludeServer()+"%")));
//		}
		if(view.getIncludeWords()!=null&&view.getIncludeWords().trim().length()>0){
			String [] includeWords = view.getIncludeWords().split("\\s");
			for (String includeWord : includeWords) {
				if(includeWord.trim().length()>0)
				searchCriteria.add(Restrictions.like("path", "%"+includeWord+"%"));
			}
		}
		
		if(view.getExcludeWords()!=null&&view.getExcludeWords().trim().length()>0) {
			String [] excludeWords = view.getExcludeWords().split("\\s");
			for(String excludeWord :excludeWords) {
				if(excludeWord.trim().length()>0)
				searchCriteria.add(Restrictions.not(Restrictions.like("path","%"+excludeWord+"%")));
			}
		}
		
		try {
			long sizeMin = Long.valueOf(view.getSizeMin());

			searchCriteria.add(Restrictions.ge("fileSize", sizeMin));
		} catch (NumberFormatException ex) {}
		
		
		try {
			long sizeMax = Long.valueOf(view.getSizeMax());
			searchCriteria.add(Restrictions.le("fileSize", sizeMax));
		} catch (NumberFormatException ex) {
			
		}
		
		if(!order) return;
		
		if(view.getOrderBy()!=null&&"ASC".equals(view.getOrderDirection())){
			searchCriteria.addOrder(Order.asc(view.getOrderBy()));
		} else if(view.getOrderBy()!=null&&"DESC".equals(view.getOrderDirection())) {
			searchCriteria.addOrder(Order.desc(view.getOrderBy()));
		}
	}
			
}
